package com.example.excelimporter.service.impl;

import com.alibaba.excel.EasyExcel;
import com.example.excelimporter.listener.ExcelDataListener;
import com.example.excelimporter.model.ImportResult;
import com.example.excelimporter.model.TemplateConfig;
import com.example.excelimporter.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class ExcelImportServiceImpl implements ExcelImportService {

    @Autowired
    private TemplateConfigService templateConfigService;

    @Autowired
    private DataValidationService dataValidationService;
    
    @Autowired
    private DataMappingService dataMappingService;
    
    @Autowired
    private DataSaveService dataSaveService;

    @Override
    public ImportResult importExcel(MultipartFile file, String templateId) throws IOException {
        TemplateConfig templateConfig = templateConfigService.getTemplateConfigById(templateId);
        if (templateConfig == null) {
            throw new IllegalArgumentException("Template not found");
        }

        // 创建监听器
        ExcelDataListener listener = new ExcelDataListener(
            templateConfig,
            dataValidationService,
            dataMappingService,
            dataSaveService
        );

        // 读取Excel文件
        EasyExcel.read(file.getInputStream(), templateConfig.getDataClass(), listener)
                .sheet()
                .doRead();

        return listener.buildImportResult();
    }
}
